<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-operator">
        <a-input-search v-model="search" placeholder="输入资源路径或者请求方法" @search="$refs.table.refresh(true)" style="width: 300px; margin-top:10px; margin-right: 20px"/>
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
        <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>
            <!-- lock | unlock -->
            <a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :alert="false"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <div
          slot="filterDropdown"
          slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
          style="padding: 8px"
        >
          <a-input
            v-ant-ref="c => (searchInput = c)"
            :placeholder="`Search ${column.dataIndex}`"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block;"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
            @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          />
          <a-button
            type="primary"
            icon="search"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          >
            Search
          </a-button>
          <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
            Reset
          </a-button>
        </div>
        <a-icon
          slot="filterIcon"
          slot-scope="filtered"
          type="search"
          :style="{ color: filtered ? '#108ee9' : undefined }"
        />
        <template slot="customRender" slot-scope="text, record, index, column">
          <span v-if="searchText && searchedColumn === column.dataIndex">
            <template
              v-for="(fragment, i) in text
                .toString()
                .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
            >
              <mark
                v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                :key="i"
                class="highlight"
              >{{ fragment }}</mark
              >
              <template v-else>{{ fragment }}</template>
            </template>
          </span>
          <template v-else>
            {{ text }}
          </template>
        </template>
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="method" slot-scope="text">
          <a-badge :status="text | methodTypeFilter" :text="text | methodFilter" />
        </span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="50" tooltip>{{ text }}</ellipsis>
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)">删除</a>
          </template>
        </span>
      </s-table>
      <step-by-step-modal ref="modal" @ok="handleOk"/>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis } from '@/components'

import StepByStepModal from '../system/modules/StepByStepModal'
import request from '@/utils/request'

const qs = require('qs')

const columns = [
  {
    title: '资源路径',
    dataIndex: 'url',
    sorter: true,
    width: '15%',
    scopedSlots: {
      filterDropdown: 'filterDropdown',
      filterIcon: 'filterIcon',
      customRender: 'customRender'
    }
  },
  {
    title: '请求方法',
    dataIndex: 'method',
    scopedSlots: { customRender: 'method' },
    sorter: true,
    filters: [
      { text: 'GET', value: 'GET' },
      { text: 'POST', value: 'POST' },
      { text: 'PUT', value: 'PUT' },
      { text: 'DELETE', value: 'DELETE' }
    ]
  },
  {
    title: '返回状态',
    dataIndex: 'status',
    sorter: true
  },
  {
    title: '返回描述',
    dataIndex: 'message',
    sorter: true
  },
  {
    title: '访问用户',
    dataIndex: 'createdBy',
    sorter: true
  },
  {
    title: '对端地址',
    dataIndex: 'remoteAddress',
    sorter: true
  },
  {
    title: '更新时间',
    width: '10%',
    dataIndex: 'updatedAt',
    sorter: true
  },
  {
    title: '请求参数',
    dataIndex: 'request',
    ellipsis: true,
    scopedSlots: { customRender: 'description' }
  },
  {
    title: '响应结果',
    dataIndex: 'response',
    ellipsis: true,
    scopedSlots: { customRender: 'description' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

const methodMap = {
  GET: {
    status: 'default', // default/processing/success/error
    text: 'GET'
  },
  POST: {
    status: 'success',
    text: 'POST'
  },
  PUT: {
    status: 'processing',
    text: 'PUT'
  },
  DELETE: {
    status: 'error',
    text: 'DELETE'
  }
}

function getLogList (parameter) {
  return request({
    url: '/alpha-gateway/logs',
    method: 'get',
    params: parameter,
    paramsSerializer: params => {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    }
  })
}

export default {
  name: 'GatewayLogList',
  components: {
    STable,
    Ellipsis,
    StepByStepModal
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      search: null,
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, { search: this.search })
        console.log('loadData request parameters:', requestParameters)
        return getLogList(requestParameters)
          .then(res => {
            return res.result
          })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {
    methodFilter (type) {
      return methodMap[type].text
    },
    methodTypeFilter (type) {
      return methodMap[type].status
    }
  },
  created () {
    // getRoleList({ t: new Date() })
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleSearch (selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },
    handleReset (clearFilters) {
      clearFilters()
      this.searchText = ''
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      const pager = { ...this.pagination }
      this.current = pagination.current
      this.pagination = pager
      const orders = (sorter && sorter.order) ? { orders: (sorter.order === 'ascend') ? sorter.field : '-' + sorter.field } : {}
      const search = {}
      console.log(filters)
      console.log(sorter)
      console.log(this.searchedColumn)
      if (this.searchedColumn) {
        search[this.searchedColumn + '~'] = this.searchText
      }
      this.fetch({
        size: pagination.pageSize,
        current: pagination.current,
        ...search,
        ...orders,
        // sortOrder: sorter.order,
        ...filters
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('修改成功')
            })
          } else {
            // 新增
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('新增成功')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleDel (record) {
      this.$message.info(`${record.url} 删除成功`)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>
